package com.qilu.pe.ui.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatEditText;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.contrarywind.interfaces.IPickerViewData;
import com.google.gson.Gson;
import com.qilu.pe.R;
import com.qilu.pe.base.Base2Activity;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Global;
import com.qilu.pe.dao.bean.JsonBean;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.GetJsonDataUtil;
import com.qilu.pe.support.util.ViewUtil;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.util.ToastUtils;

import org.json.JSONArray;

import java.util.ArrayList;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class RealAuthAgentActivity extends Base2Activity {
    private RelativeLayout rl_addr;
    private TextView tv_addr, tv_type, tv_ok;// 区域 机构类型
    private AppCompatEditText et_charge, et_id, et_agent_name, et_licence;// 用户名 身份证 机构名称 许可证
    private AppCompatEditText et_addr, et_phone;// 详细地址 业务员电话
    private RadioButton rb_1;// 男RadioButton
    private TextView tv_charge0, tv_sex0, tv_id0, tv_agent_name0, tv_agent_type0, tv_licence0, tv_addr0;

    private String address;// 记录选择器选择的地址
    private String type;// 记录选择器选择的机构类型
    private String charge, sex, id, agent_name, licence, addr, phone;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_real_auth_agent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rl_addr = findViewById(R.id.rl_addr);
        tv_addr = findViewById(R.id.tv_addr);
        tv_type = findViewById(R.id.tv_type);
        et_charge = findViewById(R.id.et_charge);
        et_id = findViewById(R.id.et_id);
        et_agent_name = findViewById(R.id.et_agent_name);
        et_licence = findViewById(R.id.et_licence);
        et_addr = findViewById(R.id.et_addr);
        et_phone = findViewById(R.id.et_phone);
        rb_1 = findViewById(R.id.rb_1);
        tv_ok = findViewById(R.id.tv_ok);
        tv_charge0 = findViewById(R.id.tv_charge0);
        tv_sex0 = findViewById(R.id.tv_sex0);
        tv_id0 = findViewById(R.id.tv_id0);
        tv_agent_name0 = findViewById(R.id.tv_agent_name0);
        tv_agent_type0 = findViewById(R.id.tv_agent_type0);
        tv_licence0 = findViewById(R.id.tv_licence0);
        tv_addr0 = findViewById(R.id.tv_addr0);

        ViewUtil.setImportantText(tv_charge0, "*用户姓名");
        ViewUtil.setImportantText(tv_sex0, "*性别");
        ViewUtil.setImportantText(tv_id0, "*身份证号");
        ViewUtil.setImportantText(tv_agent_name0, "*机构名称");
        ViewUtil.setImportantText(tv_agent_type0, "*机构类型");
        ViewUtil.setImportantText(tv_licence0, "*许可证");
        ViewUtil.setImportantText(tv_addr0, "*详细地址");

        setHeadTitle("实名机构认证");

        setListeners();
    }

    private void setListeners() {
        setOnClickListener(rl_addr, tv_type, tv_ok);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == rl_addr) {
            initJsonData();
            ShowPickerView();
        }
        if (v == tv_type) {
            initCustomOptionPicker();
            pvCustomOptions.show();
        }
        if (v == tv_ok) {
            charge = et_charge.getText().toString().trim();
            if (TextUtils.isEmpty(charge)) {
                ToastUtils.showShort("请填写用户姓名");
                return;
            }
            sex = rb_1.isChecked() ? "0" : "1";
            id = et_id.getText().toString().trim();
            if (TextUtils.isEmpty(id)) {
                ToastUtils.showShort("请填写身份证号");
                return;
            }
            agent_name = et_agent_name.getText().toString().trim();
            if (TextUtils.isEmpty(agent_name)) {
                ToastUtils.showShort("请填写机构名称");
                return;
            }
            licence = et_licence.getText().toString().trim();
            if (TextUtils.isEmpty(licence)) {
                ToastUtils.showShort("请输入许可证");
                return;
            }
            address = tv_addr.getText().toString().trim();
            if (TextUtils.isEmpty(address)) {
                ToastUtils.showShort("请选择省市区");
                return;
            }
            addr = et_addr.getText().toString().trim();
            if (TextUtils.isEmpty(addr)) {
                ToastUtils.showShort("请输入详细信息");
                return;
            }
            addr = address + addr;
            phone = et_phone.getText().toString().trim();// 业务员电话

            hideProgress();
            reqRealAuthAgent();
            showProgressWithText(true, "提交中");
        }
    }

    private Disposable reqRealAuthAgent() {
        return APIRetrofit.getDefault().reqRealAuthAgent(Global.USER_ID, "", sex, charge, id
                , agent_name, type, licence, address, addr, phone)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            ToastUtils.showShort(baseResult2.getMsg());
                            finish();
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("认证错误,请重试");
                    }
                });
    }

    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    private void initJsonData() {//解析数据
//         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
//         * 关键逻辑在于循环体
        String JsonData = new GetJsonDataUtil().getJson(this, "city.json");//获取assets目录下的json文件数据
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

//         * 添加省份数据
//         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
//         * PickerView会通过getPickerViewText方法获取字符串显示出来。
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getAreaList() == null || jsonBean.get(i).getCityList().get(c).getAreaList().size() == 0) {
                    City_AreaList.add("");
                } else {
                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getAreaList().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getAreaList().get(d).getName();
                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }
            //添加城市数据
            options2Items.add(CityList);
            //添加地区数据
            options3Items.add(Province_AreaList);
        }
    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }

    private void ShowPickerView() {// 弹出选择器
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String opt1tx = options1Items.size() > 0 ? options1Items.get(options1).getPickerViewText() : "";
                String opt2tx = options2Items.size() > 0 && options2Items.get(options1).size() > 0 ? options2Items.get(options1).get(options2) : "";
                String opt3tx = options2Items.size() > 0 && options3Items.get(options1).size() > 0 && options3Items.get(options1).get(options2).size() > 0 ? options3Items.get(options1).get(options2).get(options3) : "";

                String tx = opt1tx + opt2tx + opt3tx;
                address = tx;
                tv_addr.setText(address);
            }
        })
                .setTitleText("选择区域")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private ArrayList<CardBean> typeList = new ArrayList<>();

    private OptionsPickerView pvCustomOptions;// 条件选择器

    /**
     * @description 注意事项：自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针。
     * 具体可参考demo 里面的两个自定义layout布局。
     */
    private void initCustomOptionPicker() {//条件选择器初始化，自定义布局
        pvCustomOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = typeList.get(options1).getPickerViewText();
                type = "" + typeList.get(options1).getId();
                tv_type.setText(tx);
            }
        }).setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
            @Override
            public void customLayout(View v) {
                final TextView tvSubmit = v.findViewById(R.id.tv_finish);
                ImageView ivCancel = v.findViewById(R.id.iv_cancel);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvCustomOptions.returnData();
                        pvCustomOptions.dismiss();
                    }
                });

                ivCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvCustomOptions.dismiss();
                    }
                });
            }
        })
                .isDialog(true)
                .setOutSideCancelable(false)
                .build();

        getCardData();
        pvCustomOptions.setPicker(typeList);//添加数据
    }

    private void getCardData() {
        typeList.clear();
        // 1 综合性医院 2 社区卫生服务中心 3 门诊部/诊所/卫生所/医务室/村卫生室 4 采供血机构
        typeList.add(new CardBean(1, "综合性医院"));
        typeList.add(new CardBean(2, "社区卫生服务中心"));
        typeList.add(new CardBean(3, "门诊部/诊所/卫生所/医务室/村卫生室"));
        typeList.add(new CardBean(4, "采供血机构"));
    }

    // 机构类型(选项前端写死 1 综合性医院 2 社区卫生服务中心 3 门诊部/诊所/卫生所/医务室/村卫生室 4 采供血机构)
    public class CardBean implements IPickerViewData {
        int id;
        String cardNo;

        public CardBean(int id, String cardNo) {
            this.id = id;
            this.cardNo = cardNo;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getCardNo() {
            return cardNo;
        }

        public void setCardNo(String cardNo) {
            this.cardNo = cardNo;
        }

        @Override
        public String getPickerViewText() {
            return cardNo;
        }
    }
}